<?php
namespace app\api\logic;
use services\WxService;
use services\WxBizDataCryptService;
use think\Db;
use think\Request;
use think\Exception;
use think\facade\Cookie;
use think\facade\Session;
class Login extends Base
{
    //三方登陆
    public function thirdByUserLogin($param)
    {
        $sid = isset($param['sid'])?$param['sid']:0;
        write_log(json_encode($param));
        // $param['session_key'] = 'HRaF99PhYkC9yF+rFVJOzQ==';
        // $param['iv'] = 'fGIsn31lQiiXioSrYZ/1Ww==';
        // $param['encryptedData'] = 'qitGMF6noc4bNcpaliZ2rLGumn4E6jWQ//MiYF+71CGZZblcY3Tt8sSfVX569d9z9+cRTie2H0HQqUqmsPhRmaSFVvBfWtTGpUP64XSaTuyiLP5GqGhX60uQJJjufZF9hIBpv0Kezn+cO/C3R+7YQtYXLsZBFFgj0uFf/W3iRz1oRYZFGoZV5wnN9S9ijnuWbd6VCV8eD/GTzYANoHPRZg==';
        if (!isset($param['iv']) || !isset($param['encryptedData']) || !isset($param['openId']) || !isset($sid)) {
            $this->return_data['Msg'] = "参数不正确";
            return $this->return_data;
        }
        $param['session_key'] = cache($param['openId']);
        $WxBizDataCryptService = new WxBizDataCryptService(config('appid'),$param['session_key']);
        $result = [];
        $res = $WxBizDataCryptService->decryptData($param['encryptedData'],$param['iv'],$result);
        if ($res!=0) {
            $this->return_data['Msg'] = "参数有误";
            return $this->return_data;
        }
        $result2 = json_decode($result,1);
        $phone = '';
        if (isset($result2['phoneNumber'])) {
            $phone = $result2['phoneNumber'];
        }
        // $this->return_data['Code'] =0;
        // $this->return_data['Data'] =['token'=>'fgbVCAbV3AaOoeYDGhpv7couE9edkHN:Hq5WvauF3Ov:mya1LWmPToJ1VsUedZsF'];
        // return $this->return_data;
        $now_time = time();
        // $appid = config('appid');
        // $appsecret = config('appsecret');
        $ip = request()->ip();
        // if (empty($param['code'])) {
        //     $this->return_data['Msg'] = "code 为空";
        //     return $this->return_data;
        // }
        // $code = $param['code'];
        // $WxService = new WxService(['appid'=>$appid,'appsecret'=>$appsecret]);
        // $tokenArr = $WxService->getSessionToken(["code"=>$code]);
        // if(!isset($tokenArr['openid'])){
        //     $this->return_data['Msg'] = "进入小程序失败";
        //     return $this->return_data;
        // }
        //write_store_log("storeapi_login=========weixin========".json_encode($tokenArr));
        //判断微信用户信息是否获取到
        $openid = $param['openId'];
        $session_key = $param['session_key'];
        Db::startTrans();
        try{
            $user_log_type='login';
            $user = Db::name('user')->where([['phone','=',$phone],['sid','=',$sid],['status','=',1]])->find();
            //如果存在三方信息账号，则刷新session_key
            if (isset($user['id'])) {
                if (isset($user['openid']) && $user['openid']) {
                    if ($openid!=$user['openid']) {
                        Db::rollback();
                        $this->return_data['Msg'] = $phone."该手机号已绑定其他微信，请使用绑定的微信登录".$openid;
                        return $this->return_data;
                    }
                    $wx_info = Db::name('wx_info')->where('uid',$user['id'])->find();
                    $res = Db::name('wx_info')->where([['uid','=',$user['id']]])->update(['session_key'=>$param['session_key'],'update_time'=>$now_time]);
                    $uppdate=Db::name('user')->where('id',$user['id'])
                          ->data(['update_time'=>$now_time,'login_time'=>$now_time,'last_time'=>$user['login_time'],'login_num'=>intval($user['login_num'])+1,'login_ip'=>$ip,'last_ip'=>$user['login_ip']])->update();
                    $token_data['uid']=$return_data['uid'] = $user['id'];
                    $return_data['phone']=$user['phone'];
                } else {
                    $unionid = isset($param['unionid'])?$param['unionid']:'';
                    $userdata = ['openid'=>$openid,'unionid'=>$unionid,'create_time'=>$now_time,'login_time'=>$now_time,'login_ip'=>$ip,'login_ip'=>$ip,'login_num'=>1];
                    // $userdata['nickname'] = $param['nickName'];
                    // $userdata['avatar'] = $param['headImgUrl'];
                    $auser_insert=Db::name('user')->where(['id'=>$user['id']])->update($userdata);
                    if(!$auser_insert){
                        Db::rollback();
                        $this->return_data['Msg'] = "创建帐号失败";
                        return $this->return_data;
                    }
                    $auser_insert = $user['id'];
                    $widata['uid'] = $auser_insert;
                    $widata['openid'] = $openid;
                    // $widata['gender'] = $param['gender'];
                    // $widata['nickname'] = $param['nickName'];
                    // $widata['country'] = $param['country'];
                    // $widata['province'] = $param['province'];
                    // $widata['city'] = $param['city'];
                    // $widata['avatar'] = $param['headImgUrl'];
                    $widata['session_key'] = $session_key;
                    $widata['create_time'] = $now_time;
                    $wiinsert=Db::name('wx_info')->insertGetId($widata);
                    if(!$wiinsert){
                        Db::rollback();
                        $this->return_data['Msg'] = "创建帐号失败";
                        return $this->return_data;
                    }
                    $return_data['phone']=$phone;
                    $token_data['uid']=$return_data['uid'] = $auser_insert;
                }
            } else {
                $user_log_type='reg';
                $unionid = isset($param['unionid'])?$param['unionid']:'';
                $userdata = ['phone'=>$phone,'openid'=>$openid,'unionid'=>$unionid,'create_time'=>$now_time,'login_time'=>$now_time,'login_ip'=>$ip,'login_ip'=>$ip,'login_num'=>1,'sid'=>$sid,'study_status'=>1];
                // $userdata['nickname'] = $param['nickName'];
                // $userdata['avatar'] = $param['headImgUrl'];
                $auser_insert=Db::name('user')->insertGetId($userdata);
                if(!$auser_insert){
                    Db::rollback();
                    $this->return_data['Msg'] = "创建帐号失败";
                    return $this->return_data;
                }
                $widata['uid'] = $auser_insert;
                $widata['openid'] = $openid;
                // $widata['gender'] = $param['gender'];
                // $widata['nickname'] = $param['nickName'];
                // $widata['country'] = $param['country'];
                // $widata['province'] = $param['province'];
                // $widata['city'] = $param['city'];
                // $widata['avatar'] = $param['headImgUrl'];
                $widata['session_key'] = $session_key;
                $widata['create_time'] = $now_time;
                $wiinsert=Db::name('wx_info')->insertGetId($widata);
                if(!$wiinsert){
                    Db::rollback();
                    $this->return_data['Msg'] = "创建帐号失败";
                    return $this->return_data;
                }
                $return_data['phone']=$phone;
                $token_data['uid']=$return_data['uid'] = $auser_insert;
            }
            $token_data['created_at'] = $now_time;
            $token_data['expires_in'] = 7200;
            $token_data['ip'] = $ip;
            $token = $this->createUserToken($token_data);
            $update = Db::name('user')->where('id',$token_data['uid'])->data(['user_token'=>$token,'update_time'=>time()])->update();
            if(!$update || empty($token)){
                Db::rollback();
                $this->return_data['Msg'] = "登录失败,服务器繁忙";
                return $this->return_data;
            }
            $return_data['token']=$token;
            Db::commit();
        }catch(Exception $e){
            Db::rollback();
	    write_log($e);
	    $this->return_data['Msg'] = "服务器繁忙";
            return $this->return_data;
        }
        $this->return_data['Code'] =0;
        $this->return_data['Data'] =$return_data;
        return $this->return_data;
    }


    public function updateToken($input)
    {
        if (!isset($input['user_id'])) {
            $this->return_data['Msg'] = "参数有误";
            return $this->return_data;
        }
        $ip = request()->ip();
        $user = Db::name('user')->where([['id','=',$input['user_id']]])->find();
        $wx_info = Db::name('wx_info')->where('uid',$input['user_id'])->find();
        $uppdate=Db::name('user')->where('id',$input['user_id'])
              ->data(['update_time'=>time(),'login_time'=>time(),'last_time'=>$user['login_time'],'login_num'=>intval($user['login_num'])+1,'login_ip'=>$ip,'last_ip'=>$user['login_ip']])->update();
        $token_data['uid']=$return_data['uid'] = $input['user_id'];
        $return_data['phone']=$user['phone'];
        $token_data['created_at'] = time();
        $token_data['expires_in'] = 7200;
        $token_data['ip'] = $ip;
        $token = $this->createUserToken($token_data);
        $update = Db::name('user')->where('id',$token_data['uid'])->data(['user_token'=>$token,'update_time'=>time()])->update();
        if(!$update || empty($token)){
            $this->return_data['Msg'] = "登录失败,服务器繁忙";
            return $this->return_data;
        }
        $this->return_data['Code'] =0;
        $this->return_data['Data'] =$token;
        return $this->return_data;
    }

    /**
     *  用户头像，昵称更新 
     */
    public function userInfoUpdate($input){
        $uid = isset($input['token_user_id']) ? $input['token_user_id']:0;
        $nickname = isset($input['nickname']) ? trim($input['nickname']):'';
        $user_type = isset($input['user_type']) ? trim($input['user_type']):1;
        $avatar = isset($input['avatar']) ? trim($input['avatar']):'';
        if (!$uid || !$nickname || !$avatar){
            $this->return_data['Msg'] = " 参数错误";
            return $this->return_data;
        }
        $data['nickname']=$nickname;
        $data['user_type']=$user_type;
        $data['avatar']=$avatar;
        $data['update_time']=now_time();
        $res = Db::name('user')->where('id','=',$uid)->update($data);
        if (!$res){
            $this->return_data['Msg'] = " 更新信息失败";
            return $this->return_data;
        }
        $this->return_data['Code'] = 0;
        $this->return_data['Msg'] = "更新成功";
        return $this->return_data;
    }
    /**
     *  用户phone更新 
     */
    public function userPhoneUpdate($input){
        $uid = isset($input['token_user_id']) ? $input['token_user_id']:0;
        $phone = isset($input['phone']) ? trim($input['phone']):'';
        if (!$uid || !$phone){
            $this->return_data['Msg'] = " 参数错误";
            return $this->return_data;
        }
        $data['phone']=$phone;
        $data['update_time']=now_time();
        $res = Db::name('user')->where('id','=',$uid)->update($data);
        if (!$res){
            $this->return_data['Msg'] = " 更新信息失败";
            return $this->return_data;
        }
        $this->return_data['Code'] = 0;
        $this->return_data['Msg'] = "更新成功";
        return $this->return_data;
    }
    /**
     *  退出
     */
    public function userLogout($input){
        $uid = isset($input['token_user_id']) ? $input['token_user_id']:0;
        $data['user_token']='';$data['update_time']=now_time();
        $res = Db::name('user')->where('id','=',$uid)->update($data);
        if (!$res){
            $this->return_data['Msg'] = "退出失败";
            return $this->return_data;
        }
        $this->return_data['Code'] = 0;
        $this->return_data['Msg'] = "退出成功";
        return $this->return_data;
    }
}

